package com.bantang.controller;

import cn.hutool.core.io.FileUtil;
import com.bantang.annotation.AuthCheck;
import com.bantang.bizmq.BiMessageProducer;
import com.bantang.common.BaseResponse;
import com.bantang.common.DeleteRequest;
import com.bantang.common.ErrorCode;
import com.bantang.common.ResultUtils;
import com.bantang.constant.CommonConstant;
import com.bantang.constant.UserConstant;
import com.bantang.exception.BusinessException;
import com.bantang.exception.ThrowUtils;
import com.bantang.manager.AiManager;
import com.bantang.manager.RedisLimiterManager;
import com.bantang.model.dto.chart.*;
import com.bantang.model.entity.Chart;
import com.bantang.model.entity.User;
import com.bantang.model.vo.BiVO;
import com.bantang.service.ChartService;
import com.bantang.service.UserService;
import com.bantang.utils.ExcelUtils;
import com.bantang.utils.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

import static com.bantang.bizmq.BiMqConstant.BI_EXCHANGE_NAME;
import static com.bantang.bizmq.BiMqConstant.BI_ROUTING_KEY;


/**
 *

 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    ThreadPoolExecutor threadPoolExecutor;

    @Resource
    BiMessageProducer biMessageProducer;


    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);

        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());

        boolean charData = chartService.save(chart);
        ThrowUtils.throwIf(!charData, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);


        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean charData = chartService.updateById(chart);
        return ResultUtils.success(charData);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                     HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {


        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));

        return ResultUtils.success(chartPage);
    }

    // endregion


    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);

        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean charData = chartService.updateById(chart);
        return ResultUtils.success(charData);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }

        Long id = chartQueryRequest.getId();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();

        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();
        String name = chartQueryRequest.getName();

        queryWrapper.eq(id != null && id > 0,"id",id);
        queryWrapper.eq(StringUtils.isNotBlank(goal),"goal",goal);
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq(userId != null && userId > 0, "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 智能分析 (同步)
     * @param multipartFile
     * @param genChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<BiVO> genChartByAI(@RequestPart("file") MultipartFile multipartFile,
                                           GenChartByAIRequest genChartByAIRequest, HttpServletRequest request) {

        String name = genChartByAIRequest.getName();
        String goal = genChartByAIRequest.getGoal();
        String chartType = genChartByAIRequest.getChartType();

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length()>100, ErrorCode.PARAMS_ERROR,"名字过长");

        /**
         * 校验文件
         * 首先，拿到用户请求文件；
         * 取到原始文件大小
         */
        long size = multipartFile.getSize();

        String originalName = multipartFile.getOriginalFilename();

        /**
         * 校验文件大小
         *
         * 定义一个常量标识 1MB
         * 1M = 1024*1024字节byte
         */
        final long ONE_MB = 1024*1024L;
        //如果文件超过1M 就抛出异常 并告诉用户超过1M
        ThrowUtils.throwIf(size>ONE_MB, ErrorCode.PARAMS_ERROR,"文件超过1M");

        /**
         * 校验文件后缀
         */
        String suffix = FileUtil.getSuffix(originalName);

        List<String> validFileSuffix = Arrays.asList("xlsx","xls");
        //如果文件后缀不在validFileSuffix范围内 则抛出异常

        ThrowUtils.throwIf(!validFileSuffix.contains(suffix), ErrorCode.PARAMS_ERROR,"非法文件后缀");

        StringBuilder messageBuilder = new StringBuilder();
        if (StringUtils.isNotBlank(chartType)){
            goal += "请使用"+chartType;
        }
        messageBuilder.append("分析需求：").append("\n");
        messageBuilder.append(goal).append("\n");
        //读取Excel文件 进行处理
        String charData = ExcelUtils.excelToCsv(multipartFile);
        messageBuilder.append("原始数据："+charData).append("\n");

        User user = userService.getLoginUser(request);

        redisLimiterManager.doRateLimit(user.getId()+"");
        //调用AI接口分析数据
        String verdictMessage = aiManager.doChat(messageBuilder.toString());

        verdictMessage = verdictMessage.replaceAll("】】】】】","【【【【【");

        String verdictMessages[] = verdictMessage.split("【【【【【");


        if (verdictMessages.length < 3){
            return ResultUtils.error(999,"AI生成错误");
        }

        String genChart = verdictMessages[1].trim();
        String genResult = verdictMessages[2].trim();

        Chart chart = new Chart();

        chart.setName(name);
        chart.setGoal(goal);
        chart.setUserId(user.getId());
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);

        boolean saveResult = chartService.save(chart);

        ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR,"图表保存失败");

        //图表保存成功后 将用户原始数据存入数据库  采用存表原则 将用户数据直接存一张表中
        //拿到所有列名
        chartService.saveData(charData,user.getId(),chart.getId());

        BiVO biVO = new BiVO();

        biVO.setGenChart(genChart);
        biVO.setGenResult(genResult);
        biVO.setChartId(chart.getId());
        return ResultUtils.success(biVO);

    }

    /**
     * 智能分析 (异步)（线程池）
     * @param multipartFile
     * @param genChartByAIRequest
     * @param request
     * @return
     */
//    @PostMapping("/uploadAsync")
//    public BaseResponse<BiVO> genChartByAIAsync(@RequestPart("file") MultipartFile multipartFile,
//                                           GenChartByAIRequest genChartByAIRequest, HttpServletRequest request) {
//
//        String name = genChartByAIRequest.getName();
//        String goal = genChartByAIRequest.getGoal();
//        String chartType = genChartByAIRequest.getChartType();
//
//        //校验
//        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
//        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length()>100,ErrorCode.PARAMS_ERROR,"名字过长");
//
//        /**
//         * 校验文件
//         *
//         * 首先，拿到用户请求文件；
//         * 取到原始文件大小
//         */
//        long size = multipartFile.getSize();
//
//        String originalName = multipartFile.getOriginalFilename();
//
//        /**
//         * 校验文件大小
//         *
//         * 定义一个常量标识 1MB
//         * 1M = 1024*1024字节byte
//         */
//        final long ONE_MB = 1024*1024L;
//        //如果文件超过1M 就抛出异常 并告诉用户超过1M
//        ThrowUtils.throwIf(size>ONE_MB,ErrorCode.PARAMS_ERROR,"文件超过1M");
//
//        /**
//         * 校验文件后缀
//         */
//        String suffix = FileUtil.getSuffix(originalName);
//
//        List<String> validFileSuffix = Arrays.asList("xlsx","xls");
//        //如果文件后缀不在validFileSuffix范围内 则抛出异常
//
//        ThrowUtils.throwIf(!validFileSuffix.contains(suffix),ErrorCode.PARAMS_ERROR,"非法文件后缀");
//
//        StringBuilder messageBuilder = new StringBuilder();
//        if (StringUtils.isNotBlank(chartType)){
//            goal += "请使用"+chartType;
//        }
//        messageBuilder.append("分析需求：").append("\n");
//        messageBuilder.append(goal).append("\n");
//        //读取Excel文件 进行处理
//        String charData = ExcelUtils.excelToCsv(multipartFile);
//        messageBuilder.append("原始数据："+charData).append("\n");
//
//        User user = userService.getLoginUser(request);
//
//        redisLimiterManager.doRateLimit(user.getId()+"");
//
//
//        Chart chart = new Chart();
//
//        chart.setName(name);
//        chart.setGoal(goal);
//        chart.setUserId(user.getId());
//        chart.setChartType(chartType);
//        chart.setStatus("wait");
////        chart.setGenChart(genChart);
////        chart.setGenResult(genResult);
//
//        boolean saveResult = chartService.save(chart);
//
//        ThrowUtils.throwIf(!saveResult,ErrorCode.OPERATION_ERROR,"图表保存失败");
//
//        //图表保存成功后 将用户原始数据存入数据库  采用存表原则 将用户数据直接存一张表中
//        //拿到所有列名
//        chartService.saveData(charData,user.getId(),chart.getId());
//
//
//        CompletableFuture.runAsync(
//                ()->{
//                    Chart updateChart = new Chart();
//                    updateChart.setId(chart.getId());
//                    updateChart.setStatus("running");
//                    boolean b = chartService.updateById(updateChart);
//
//                    if (!b){
//                        handleCharUpdateError(chart.getId(),"更改图表执行中状态失败");
//                    }
//
//                    //调用AI接口分析数据
//                    String verdictMessage = aiManager.doChat(messageBuilder.toString());
//
//                    String verdictMessages[] = verdictMessage.split("【【【【【|】】】】】");
//
//                    if (verdictMessages.length < 3){
//                         ResultUtils.error(999,"AI生成错误");
//                    }
//
//                    String genChart = verdictMessages[1].trim();
//                    String genResult = verdictMessages[2].trim();
//
//                    Chart updateChartResult = new Chart();
//                    updateChartResult.setId(chart.getId());
//                    updateChartResult.setStatus("succeed");
//                    updateChartResult.setGenChart(genChart);
//                    updateChartResult.setGenResult(genResult);
//
//                    boolean updateResult = chartService.updateById(updateChartResult);
//
//                    if (!updateResult){
//                        handleCharUpdateError(chart.getId(),"图表成功状态更新失败");
//                    }
//
//
//                },threadPoolExecutor
//        );
//
//        BiVO biVO = new BiVO();
//
////        biVO.setGenChart(genChart);
////        biVO.setGenResult(genResult);
//        biVO.setChartId(chart.getId());
//        return ResultUtils.success(biVO);
//
//    }



    /**
     * 智能分析 (异步)（消息队列）
     * @param multipartFile
     * @param genChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/uploadAsync")
    public BaseResponse<BiVO> genChartByAIAsync(@RequestPart("file") MultipartFile multipartFile,
                                                GenChartByAIRequest genChartByAIRequest, HttpServletRequest request) {

        String name = genChartByAIRequest.getName();
        String goal = genChartByAIRequest.getGoal();
        String chartType = genChartByAIRequest.getChartType();

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length()>100, ErrorCode.PARAMS_ERROR,"名字过长");

        /**
         * 校验文件
         *
         * 首先，拿到用户请求文件；
         * 取到原始文件大小
         */
        long size = multipartFile.getSize();

        String originalName = multipartFile.getOriginalFilename();

        /**
         * 校验文件大小
         *
         * 定义一个常量标识 1MB
         * 1M = 1024*1024字节byte
         */
        final long ONE_MB = 1024*1024L;
        //如果文件超过1M 就抛出异常 并告诉用户超过1M
        ThrowUtils.throwIf(size>ONE_MB, ErrorCode.PARAMS_ERROR,"文件超过1M");

        /**
         * 校验文件后缀
         */
        String suffix = FileUtil.getSuffix(originalName);

        List<String> validFileSuffix = Arrays.asList("xlsx","xls");
        //如果文件后缀不在validFileSuffix范围内 则抛出异常

        ThrowUtils.throwIf(!validFileSuffix.contains(suffix), ErrorCode.PARAMS_ERROR,"非法文件后缀");

        StringBuilder messageBuilder = new StringBuilder();
        if (StringUtils.isNotBlank(chartType)){
            goal += "请使用"+chartType;
        }
        messageBuilder.append("分析需求：").append("\n");
        messageBuilder.append(goal).append("\n");
        //读取Excel文件 进行处理
        String charData = ExcelUtils.excelToCsv(multipartFile);
        messageBuilder.append("原始数据："+charData).append("\n");

        User user = userService.getLoginUser(request);

        redisLimiterManager.doRateLimit(user.getId()+"");


        Chart chart = new Chart();

        chart.setName(name);
        chart.setGoal(goal);
        chart.setUserId(user.getId());
        chart.setChartType(chartType);
        chart.setStatus("wait");
        chart.setChartData(charData);

        boolean saveResult = chartService.save(chart);


        ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR,"图表保存失败");

        //图表保存成功后 将用户原始数据存入数据库  采用存表原则 将用户数据直接存一张表中
        //拿到所有列名
        chartService.saveData(charData,user.getId(),chart.getId());

        biMessageProducer.sendMessage(BI_EXCHANGE_NAME,BI_ROUTING_KEY,String.valueOf(chart.getId()));

        BiVO biVO = new BiVO();

        biVO.setChartId(chart.getId());
        return ResultUtils.success(biVO);

    }

    private void handleCharUpdateError(long chartId,String errorMessage){

        Chart errorChart = new Chart();
        errorChart.setId(chartId);
        errorChart.setStatus("failed");
        errorChart.setExecMessage(errorMessage);

        boolean b = chartService.updateById(errorChart);
        if (!b){
            log.error("更新图表状态失败"+chartId+","+errorMessage);
        }
    }



}
